package com.szxy.config;

import com.alibaba.fastjson.JSON;
import com.szxy.constants.HttpStatus;
import com.szxy.vo.AjaxResult;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zwz
 * @Date:2020/7/20 23:35
 * @Description:com.szxy.conf
 * @Version:1.0 Shiro 登录过滤器
 **/
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * 设置用户拒绝登录的响应结果
     *
     * @param request  请求信息
     * @param response 响应信息
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        // 创建 vo 对象，响应结果给前端
        AjaxResult ajaxResult = AjaxResult.fail();
        ajaxResult.put("code", HttpStatus.UNAUTHORIZED);
        ajaxResult.put("msg", "登录认证失效，请重新登录!");
        httpServletResponse.getWriter().write(JSON.toJSON(ajaxResult).toString());
        return false;
    }
}
